//
// Created by gxy on 2025/8/31.
//

#include <common.h>

ListNode *removeDuplicated(ListNode *head) {
    if (head == nullptr || head->next == nullptr || head->next->next == nullptr) {
        return head;
    }
    ListNode *pre = head, *p = head->next, *then = head->next->next;
    unordered_map<int, int> mp;
    for (;;) {
        int val = p->val;
        val=abs(val);
        if (mp[val] > 0) {
            //需要删除
            pre->next=then;
            p=then;
            then=then->next;
        }else {
            pre=pre->next;
            p=p->next;
            then = then->next;
            mp[val]++;
        }
        if (then==nullptr) {
            break;
        }
    }
    int val = p->val;
    val=abs(val);
    if (mp[val]>0) {
        pre->next=nullptr;
    }
    return head;
}

int main(int argc, char *argv[]) {
    ListNode* head=ListNode::of({21,-7,15,15,6,-15});
    auto s=removeDuplicated(head);
    while(s!=nullptr) {
        cout << s->val << endl;
        s=s->next;
    }
    return 0;
}
